package com.leyou.page.service;

import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> loadItemData(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());
        // 封装结果
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);
        return map;
    }

    private static final String templateName = "item";
    private static final String HTML_DIR = "C:\\lesson\\heima90\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long spuId) {
        // 上下文，里面是模型数据
        Context context = new Context();
        context.setVariables(loadItemData(spuId));

        // 目标文件
        File file = new File(HTML_DIR, spuId + ".html");

        // 输出流，关联目标文件
        try (Writer writer = new PrintWriter(file, "UTF-8")) {
            // 生成页面
            templateEngine.process(templateName, context, writer);
        } catch (UnsupportedEncodingException e) {
            throw new LyException(500, "静态页生成失败，文件编码错误！", e);
        } catch (FileNotFoundException e) {
            throw new LyException(500, "静态页生成失败，文件不存在！", e);
        } catch (IOException e) {
            throw new LyException(500, "静态页生成失败，文件写入错误！", e);
        }
    }

    public void deleteItemHtml(Long spuId) {
        // 找到这个文件
        File file = new File(HTML_DIR, spuId + ".html");
        // 删除
        if(!file.delete()){
            // 如果删除失败，抛出异常
            throw new RuntimeException("文件删除失败！");
        }
    }
}
